<template>
  <div class="reward-multi-select">
    <!-- 自定义输入框，显示奖励气泡 -->
    <div
      class="custom-input"
      :class="{ focused: showRewardDialog }"
      @click="showRewardDialog = true"
    >
      <el-tag
        v-for="(reward, index) in selectedRewards"
        :key="index"
        closable
        @close="removeReward(index)"
        :type="getTagType(reward.name)"
        style="margin: 5px; display: inline-block;"
      >
        {{ reward.name }} ({{ reward.count }})
      </el-tag>
      <span v-if="selectedRewards.length === 0" class="placeholder">请选择奖惩项目</span>
    </div>

    <!-- 奖励选择弹窗 -->
    <el-dialog title="选择奖惩" :visible.sync="showRewardDialog" width="40%">
      <el-form label-width="100px">
        <el-form-item label="奖惩类型">
          <el-cascader
            v-model="selectedReward"
            :options="rewardOptions"
            :props="{ expandTrigger: 'hover', filterable: true, placeholder: '请输入关键词搜索' }"
            style="width: 100%;"
            @change="handleCascaderChange"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="数量">
          <el-input-number v-model="selectedRewardCount" :min="1" :max="100" label="请输入数量"></el-input-number>
          <el-button type="primary" @click="addReward">确认</el-button>
        </el-form-item>
      </el-form>

      <!-- 已添加的奖励列表 -->
      <div class="added-rewards" style="margin-top: 20px;">
        <el-tag
          v-for="(reward, index) in selectedRewards"
          :key="index"
          closable
          @close="removeReward(index)"
          :type="getTagType(reward.name)"
          style="margin: 5px; display: inline-block;"
        >
          {{ reward.name }} ({{ reward.count }})
        </el-tag>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      showRewardDialog: false,
      selectedReward: [], // 级联选择值，如 ['奖励', '一等功']
      selectedRewardCount: 1,
      selectedRewards: [],
      rewardOptions: [
        {
          label: '奖励',
          value: '奖励',
          children: [
            { label: '一等功', value: '一等功' },
            { label: '二等功', value: '二等功' },
            { label: '三等功', value: '三等功' },
            { label: '嘉奖', value: '嘉奖' },
          ]
        },
        {
          label: '表彰',
          value: '表彰',
          children: [
            { label: '一级表彰', value: '一级表彰' },
            { label: '二级表彰', value: '二级表彰' },
            { label: '三级表彰', value: '三级表彰' }
          ]
        },
        {
          label: '处分',
          value: '处分',
          children: [
            { label: '警告', value: '警告' },
            { label: '严重警告', value: '严重警告' },
            { label: '记过', value: '记过' },
            { label: '记大过', value: '记大过' }
          ]
        },
        {
          label: '无',
          value: '无',
          children: [
            { label: '无', value: '无' },
            ]
        }
      ]
    };
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        try {
          this.selectedRewards = val
            ? Object.entries(JSON.parse(val)).map(([name, count]) => ({ name, count }))
            : [];
        } catch (e) {
          this.selectedRewards = [];
        }
      }
    },
    selectedRewards: {
      deep: true,
      handler() {
        this.updateInputValue();
      }
    }
  },
  methods: {
    handleCascaderChange(value) {
      this.selectedReward = value;
    },
    addReward() {
      if (this.selectedReward.length === 2 && this.selectedRewardCount > 0) {
        const rewardName = this.selectedReward[1]; // 获取具体名称，如 "一等功"
        const existingIndex = this.selectedRewards.findIndex(r => r.name === rewardName);

        if (existingIndex > -1) {
          this.selectedRewards[existingIndex].count = this.selectedRewardCount;
        } else {
          this.selectedRewards.push({
            name: rewardName,
            count: this.selectedRewardCount
          });
        }

        this.selectedReward = [];
        this.selectedRewardCount = 1;
      }
    },
    removeReward(index) {
      this.selectedRewards.splice(index, 1);
    },
    updateInputValue() {
      const rewardObj = this.selectedRewards.reduce((acc, reward) => {
        acc[reward.name] = reward.count;
        return acc;
      }, {});
      const rewardStr = JSON.stringify(rewardObj);
      this.$emit('input', rewardStr);
    },
    getTagType(name) {
      const rewardTypes = {
        '一等功': 'warning',
        '二等功': 'warning',
        '三等功': 'warning',
        '一级表彰': 'orange',
        '二级表彰': 'orange',
        '三级表彰': 'orange',
        '警告': 'danger',
        '严重警告': 'danger',
        '记过': 'danger',
        '记大过': 'danger'
      };
      return rewardTypes[name] || '';
    }
  }
};
</script>

<style scoped>
.custom-input {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 8px 10px;
  min-height: 36px;
  box-sizing: border-box;
  cursor: pointer;
  transition: 0.2s ease;
  background-color: #fff;
}

.custom-input.focused {
  border-color: #409EFF;
}

.placeholder {
  color: #c0c4cc;
  font-size: 14px;
}

/* 自定义 el-tag 类型 */
::v-deep .el-tag--orange {
  background-color: #f5a623;
  color: #fff;
}
</style>
